#!/usr/bin/env python
# -*- encoding=utf-8 -*-
'''
Created on 2017/12/28

@author: peulerosci
'''

import logging
import json, time
import logging.config

from subprocess import *
import os, re, sys, datetime
reload(sys)
sys.setdefaultencoding('utf8')

if not os.path.isdir("log"):
    os.mkdir("log")
logging.config.fileConfig("logger.conf")
logger = logging.getLogger("copy_jenkins")


def shell_cmd(s_cmd_line, inmsg=None):
    p = Popen(s_cmd_line, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
    if inmsg:
        p.stdin.write(inmsg)
    out, err = p.communicate()
    return p.returncode, out, err


def get_gerrit_info_by_time():
    file_tmp = '/home/xdfxdf_tmp'
    cmd = 'ssh -p 29418 peulerosci@euleros-review.huawei.com gerrit query --current-patch-set \
        --patch-sets --format=JSON  branch:next after:2017-01-01 status:merged > %s' % (file_tmp)
    ret, out, err = shell_cmd(cmd)
    if ret != 0:
        logger.error("run: %s : failed,the out is %s,the err is %s" % (cmd, out, err))
        # return False
        sys.exit(1)
    f = open(file_tmp)
    for eachLine in f:
        line = eachLine.strip()
        line = line.strip(',')
        #logger.warning('1111111111111111111111111======{0}\n\n'.format(line))
        js = None
        try:
            js = json.loads(line)
        except Exception, e:
            logger.error('%s : %s' % (Exception, e))
            continue
            #sys.exit(1)

        if js.has_key('rowCount'):
            all_info.append('No more merge')
            break

        status = js.get('status')
        if status != 'MERGED':
            continue
        branch = js.get('branch')
        if branch != 'next': # or branch != 'master' or branch != 'EulerOS_V2R2C20':
            continue
        project = js.get('project')
        cmd = 'cd {0};repo sync -c {1} --no-tags --force-sync'.format('/usr1/jenkins/EulerOS_' + branch, project)
        ret, out, err = shell_cmd(cmd)
        if ret != 0:
            logger.error("run: %s : failed,the out is %s,the err is %s" % (cmd, out, err))
            sys.exit(1)

        changeid_1 = js.get('id')
        changeid = js.get('number')

        logger.info('change_num:{0}  branch:{1}  project:{2}  changeid:{3}'.format(changeid, branch, project, changeid_1))
        cmd = 'python get_changelog.py {0} {1} {2} {3}'.format(changeid, branch, project, changeid_1)
        ret, out, err = shell_cmd(cmd)
        if ret != 0:
            logger.error("run: %s : failed,the out is %s,the err is %s" % (cmd, out, err))
            #sys.exit(1)


def get_gerrit_info():
    changeids = range(19000,19300)
    for changeid in changeids:
        cmd = 'ssh -p 29418 peulerosci@dgggit09-rd.huawei.com gerrit query --current-patch-set \
        --patch-sets --format=JSON  change:"%s"' % (changeid)
        ret, out, err = shell_cmd(cmd)
        if ret != 0:
            logger.error("run: %s : failed,the out is %s,the err is %s" % (cmd, out, err))
            # return False
            #sys.exit(1)

        #print '333333333=={0}'.format(out)
        line = out.split(']}\n')[0].strip()
        line = line.strip(',') + ']}'
        #logger.warning('1111111111111111111111111======{0}\n\n'.format(line))
        js = None
        try:
            js = json.loads(line)
        except Exception, e:
            logger.error('%s : %s' % (Exception, e))
            continue
            #sys.exit(1)

        status = js.get('status')
        if status != 'MERGED':
            continue
        branch = js.get('branch')
        if branch != 'next': 
            continue
        project = js.get('project')
        cmd = 'cd {0};repo sync -c {1} --no-tags --force-sync'.format('/usr1/jenkins/EulerOS_' + branch, project)
        ret, out, err = shell_cmd(cmd)
        if ret != 0:
            logger.error("run: %s : failed,the out is %s,the err is %s" % (cmd, out, err))
            #sys.exit(1)
            continue

        changeid_1 = js.get('id')

        logger.info('change_num:{0}  branch:{1}  project:{2}  changeid:{3}'.format(changeid, branch, project, changeid_1))
        cmd = 'python get_changelog.py {0} {1} {2} {3}'.format(changeid, branch, project, changeid_1)
        ret, out, err = shell_cmd(cmd)
        if ret != 0:
            logger.error("run: %s : failed,the out is %s,the err is %s" % (cmd, out, err))
            #sys.exit(1)


# 执行之前请先在对应的目录下先repo sync所有代码
if __name__ == "__main__":
    get_gerrit_info()
    #get_gerrit_info_by_time()

